package com.woniuxy.controller;

import com.woniuxy.service.IAuthService;
import com.woniuxy.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/auth")
@Slf4j
public class AuthController {
    @Autowired
    private IAuthService iAuthService;

    @RequestMapping("/verifyLogin")
    public String  verifyLogin(String userName, String userPassword,String backUrl, HttpServletRequest request, HttpServletResponse response)  {
        boolean verify = iAuthService.verify(userName, userPassword);

        if (verify){
            //认证通过，生成token
            String token = JwtUtils.createToken(userName, 600);
            //将token信息保存到Cookie(此Cookie设置了同一个域下所有的服务可共享的Cookie:共享标识为设置path为"/")，
            //共享Cookie自动添加token在URL中,独享Cookie并不会自动添加，并且二次请求URL中不带token,Cookie会被清除
            Cookie tokenCookie = new Cookie("token",token);
            log.error("LocalAddr:{}",request.getLocalAddr());
            tokenCookie.setDomain(request.getLocalAddr());
            tokenCookie.setPath("/");
            response.addCookie(tokenCookie);
            //重定向返回来时的url
//            return "redirect:"+backUrl+"?token="+token;
            return "redirect:"+backUrl;
        }else {
            return "redirect:/login/loginUI?backUrl="+backUrl;
        }
    }
}
